package com.jugheadzhou.gateway.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * webflux 测试
 *
 * @author jugheadzhou
 * @date 2021-09-28
 */
@Slf4j
@RestController
@RequestMapping("test/")
public class TestController {

    private String createStr(){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            log.info("", e);
        }
        log.info("创建完成");
        return "testStr";
    }

    /**
     * mvc test
     *
     * @return
     */
    @GetMapping("mvc")
    public String mvcTest(){

        log.info("mvc start");
        String str = createStr();
        log.info("mvc end");
        return str;
    }

    /**
     * mono test
     *
     * @return
     */
    @GetMapping("mono")
    public Mono<?> monoTest(){
        log.info("mono start");
        Mono<String> resMono = Mono.fromSupplier(this::createStr);
        log.info("mono end");
        return resMono;

    }

    /**
     * flux test
     *
     * @return
     */
    @GetMapping(value = "flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<?> fluxTest(){
        Flux<String> flux = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception ignored) {
            }
            return "flux data -> " + i;
        }));
        return flux;
    }


}
